import { reqGetOneTileService } from "@/api/terrainrtsApi";
import axios from "axios";
import { ElMessage } from "element-plus";
import { Destroyable, Event, HasOwner, ObjResettingWithEvent, createNextAnimateFrameEvent, react } from "earthsdk3";
import { MyProjectManager } from "../MyProjectManager";
import { SwitchTerrainRts } from "./switchTerrainRts";
import { ESRTSTerrainLayer } from "../esobjs/ESRTSTerrainLayer";
import { HeightMask } from "./heightMask";
import { WaterMask } from "./waterMask";
import { ClipPolygon } from "./clipPolygon";
import { save } from "../utils";

class TerrainRtsResettting extends Destroyable {
    constructor(terrainrtsManager: TerrainRtsManager, owner: MyProjectManager) {
        super();
        const init = async () => {
            terrainrtsManager.eSRTSTerrainLayer = owner.createSceneObject(ESRTSTerrainLayer) as ESRTSTerrainLayer;
            // eSRtsTileset url
            terrainrtsManager.eSRTSTerrainLayer.url = terrainrtsManager.terrainRtsUrl
            const res = await reqGetOneTileService(terrainrtsManager.eSRTSTerrainLayer.tileServiceName)

            terrainrtsManager.eSRTSTerrainLayer.eSTerrainLayer.rectangle = [res.data.box.minX, res.data.box.maxY, res.data.box.maxX, res.data.box.minY]
            this.dispose(terrainrtsManager.eSRTSTerrainLayer.eSTerrainLayer.activateEvent.disposableOnce(() => {
                terrainrtsManager.eSRTSTerrainLayer && terrainrtsManager.eSRTSTerrainLayer.flyTo()
            }))
        }
        init()
        this.dispose(() => {
            terrainrtsManager.eSRTSTerrainLayer && owner.destroySceneObject(terrainrtsManager.eSRTSTerrainLayer)
            terrainrtsManager.eSRTSTerrainLayer = undefined
        })

    }
}

export class TerrainRtsManager extends HasOwner<MyProjectManager> {

    // 服务路径
    private _terrainRtsUrl = this.dv(react<string>(""));
    get terrainRtsUrl() { return this._terrainRtsUrl.value; }
    get terrainRtsUrlChanged() { return this._terrainRtsUrl.changed; }
    set terrainRtsUrl(value: string) { this._terrainRtsUrl.value = value; }

    // 是不是TerrainRts服务
    private _isTerrainRtsService = this.dv(react<boolean>(false));
    get isTerrainRtsService() { return this._isTerrainRtsService.value; }
    get isTerrainRtsServiceChanged() { return this._isTerrainRtsService.changed; }
    set isTerrainRtsService(value: boolean) { this._isTerrainRtsService.value = value; }

    // ESRTSTerrainLayer
    private _eSRTSTerrainLayer: undefined | ESRTSTerrainLayer = undefined;
    get eSRTSTerrainLayer() { return this._eSRTSTerrainLayer; }
    set eSRTSTerrainLayer(value: undefined | ESRTSTerrainLayer) { this._eSRTSTerrainLayer = value; }

    // 清除TerrainRts窗口
    private _clearTerrainRtsWindowEvent = this.dv(new Event());
    get clearTerrainRtsWindowEvent() { return this._clearTerrainRtsWindowEvent; }

    // 弹出框事件
    private _dialogEvent = this.dv(new Event<[string]>());
    get dialogEvent() { return this._dialogEvent; }

    // 切换terrainRts服务
    private _switchTerrainRts = this.dv(new SwitchTerrainRts(this.owner));
    get switchTerrainRts() { return this._switchTerrainRts; }

    // 高程蒙版
    private _heightMask = this.dv(new HeightMask(this.owner));
    get heightMask() { return this._heightMask; }

    // 水面蒙版
    private _waterMask = this.dv(new WaterMask(this.owner));
    get waterMask() { return this._waterMask; }

    // 裁剪多边形
    private _clipPolygon = this.dv(new ClipPolygon(this.owner));
    get clipPolygon() { return this._clipPolygon; }

    // 验证是不是TerrainRts服务
    async verifyTerrainRtsService() {
        try {
            // 添加请求头
            const token = localStorage.getItem("Authorization")
            const res2 = await axios({
                url: this.terrainRtsUrl,
                method: 'get',
                headers: {
                    ...(token ? { 'Authorization': token } : {})
                },
            })
            console.log("res2.data", res2.data);


            if (res2.data.data && res2.data.data.hasOwnProperty("schema")) {
                this.isTerrainRtsService = true
            } else {
                this.isTerrainRtsService = false
                ElMessage.error('请输入正确的TerrainRTS服务地址')
            }

        } catch (error) {
            this.isTerrainRtsService = false
            ElMessage.error('请输入正确的TerrainRTS服务地址')
            return false
        }

    }

    clear() {
        // 是否是TerrainRts服务
        this.isTerrainRtsService = false
        // 清除TerrainRts窗口
        this.clearTerrainRtsWindowEvent.emit()
        // 场景树上的对象删除
        this.owner.terrainRtsSceneTreeWrapper?.destroyAllSceneObjectTreeItems()
        this.owner.terrainRtsPropSceneTree = undefined
    }

    // 下载geojson
    downloadGeoJSON(lists: any,type: string) {
        const features = lists.map((item: any) => {
            return {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "coordinates": JSON.parse(item.geojson).coordinates,
                    "type": "Polygon"
                }
            }
        })
        const json = {
            "type": "FeatureCollection",
            "features": [
                ...features
            ]
        }
        save(json,"geojson", `${type}`);
    }

    constructor(owner: MyProjectManager) {
        super(owner);


        {
            const updata = async (url: string) => {
                // 清除参数
                this.clear()
                if (!url) {
                    this.isTerrainRtsService = false
                    return;
                }
                // 验证是不是terrainRts服务
                await this.verifyTerrainRtsService()
            }
            this.dispose(this.terrainRtsUrlChanged.don(updata))
        }
        {
            // const obj = getUrlParam();
            // this.dispose(this.eSRTSTerrainLayer.es3DTileset.tilesetReady.disposableOnce(() => {
            //     if (obj.hasOwnProperty("cameraInfo")) return;
            //     this.eSRTSTerrainLayer.es3DTileset.flyTo()
            // }))

        }

        {
            const event = this.dv(createNextAnimateFrameEvent(this.isTerrainRtsServiceChanged));
            this.dv(new ObjResettingWithEvent(event, () => {
                // terrainRts服务地址为空
                if (!this.terrainRtsUrl) return undefined;
                // 不是terrainRts服务
                if (!this.isTerrainRtsService) return undefined;
                return new TerrainRtsResettting(this, this.owner);

            }))
        }
    }
}